//
//  VerifyCodeViewController.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/2/26.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift



class VerifyCodeViewController: ViewController {
 
    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var mobileTextField: UITextField!
    @IBOutlet weak var codeTextField: UITextField!
    
    @IBOutlet weak var nextBtn: UIButton!
    @IBOutlet weak var codeBtn: UIButton!
    
    var type: LoginType!
    var verifyCode: String?
    
    static func controller(_ codeType:LoginType = .rigist) -> VerifyCodeViewController {
        let vc = VerifyCodeViewController.viewController(storyboardName: "Account") as! VerifyCodeViewController
        vc.type = codeType
        return vc
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        contentView.clipsToBounds = true
        contentView.layer.cornerRadius = 10.0
        contentView.layer.borderWidth = 0.5
        contentView.layer.borderColor = UIColor.lsf_color16(0x9c9c9c).cgColor
        
        nextBtn.clipsToBounds = true
        nextBtn.layer.cornerRadius = 10
        
        
        switch type {
        case .changePsd:
            title = "重设密码"
        default:
            title = "注册"
        }
        

        //校验手机号
        let mobileObservable:Observable<Bool> = mobileTextField.rx.text.orEmpty.distinctUntilChanged().map { text in
            var result = false
            result = (text.count == 11)
            return result
        }
        
        mobileObservable
            .subscribeOn(MainScheduler.instance)
            .subscribe(onNext: { (valid) in
            self.codeBtn.isEnabled = valid
        }).disposed(by: disposeBag)
        
        //检验验证码
        let codeObservable: Observable<Bool> = codeTextField.rx.text.orEmpty.map { text in
            var result = false
            result = (text.count >= 4)
            return result
        }
        
        
        //同时校验， 下一步
        let nextObservable:Observable<Bool> = Observable.combineLatest(mobileObservable, codeObservable)  {$0 && $1}
        nextObservable.subscribe(onNext: { (valid) in
            if valid , self.verifyCode != nil {
                self.nextBtn.isEnabled = true
                self.nextBtn.backgroundColor = UIColor.lsf_color16(0xF56E77)
            }else{
                self.nextBtn.isEnabled = false
                self.nextBtn.backgroundColor = UIColor.lightGray
            }
        }).disposed(by: disposeBag)
        
        //获取验证码、开启定时器
        codeBtn.rx.tap.bind {
            startAnimating()
            let mobile = self.mobileTextField.text ?? ""
            AccountService.getSmsAuthCode(mobile, success: { [weak self] (verifyCode) in
                stopAnimating()
                if let strongSelf = self {
                    strongSelf.codeTextField.becomeFirstResponder()
                    strongSelf.verifyCode = verifyCode
                    strongSelf.codeBtn.countDown(count: 60)
                }
                }, failure: { [weak self] (code, msg) in
                    stopAnimating()
                    lsf_alert(msg, viewController:self)
            })
            
        }.disposed(by: disposeBag)
    
        //点击下一步
        nextBtn.rx.tap.bind {
            let mobile = self.mobileTextField.text ?? ""
            let sms = self.codeTextField.text ?? ""
            self.view.endEditing(true)
            startAnimating()
            AccountService.verifySMS(mobile: mobile, verifyCode: self.verifyCode!, sms: sms, success: { [weak self]  in
                stopAnimating()
                if let strongSelf = self {
                    let setPsdVC = PasswordViewController.controller(mobile: mobile,
                                                                     verifyCode: strongSelf.verifyCode!,
                                                                     sms: sms, type: strongSelf.type)
                    strongSelf.navigationController?.pushViewController(setPsdVC, animated: true)
                }
                }, failure: { [weak self] (code, msg) in
                    stopAnimating()
                    lsf_alert(msg, viewController:self)
            })
        }.disposed(by: disposeBag)
        
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
  
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
